// packageC/pages/takeOutIndex/takeOutIndex.js
const app = getApp()
const common = require('../../../public.js')
Page({

    /**
     * 页面的初始数据
     */
    data: {
        scrollTop: 0,
        value: 5,
        shopCarShow: true,
        userInfo: {},
        orderList: ['点餐', '评价', '商家',],
        actIndex: 0,
        cateLeftList: [], //左边列表
        defaultItemList: [],
        activeId: -1, //左边s
        toView: '', //滚动目标
        isCollected: false,
        clickShow: false,//监听左侧菜单栏是否点击
        guigeShow: false, //规格
        okHeight: 0,
        showImg: false,
        pageNum: 1,
        isLoadingBusy: false, // 标记是否正在加载更多数据
        checkedImgNone: 'http://feiyangimage.oss-cn-shanghai.aliyuncs.com/wxApplets/icon/checkedNon.png',
        checkedImgDui: 'http://feiyangimage.oss-cn-shanghai.aliyuncs.com/wxApplets/icon/checkedDui.png',
        shopIschecked: false,
        shopPrice: 0,
        cartList: [],
        atherCarList: [],
        goodsNum: 0
    },
    // 购物车点击事件
    click_checked(e) {
        let { index, item } = e.currentTarget.dataset
        this.data.cartList.forEach((item, i) => {
            if (index == i) {
                item.shopIschecked = !item.shopIschecked
            }
        })
        this.setData({
            // shopPrice,
            cartList: this.data.cartList,
            atherCarList: this.data.cartList
        }, () => {
            let shopPrice;
            if (this.data.cartList[index].shopIschecked) {
                shopPrice = item.price * item.num + this.data.shopPrice

            } else {
                shopPrice = this.data.shopPrice - item.price* item.num
            }
            this.setData({
                shopPrice
            })
            //   console.log(this.data.cartList[index])

        })
    },
    // 全选中购物车
    click_allGoods() {
        this.data.shopIschecked = !this.data.shopIschecked
        this.data.cartList.forEach((item, i) => {
            item.shopIschecked = this.data.shopIschecked
        })
        let totalPrice;
        if (!this.data.shopIschecked) {
            totalPrice = 0
        } else {
            totalPrice = this.data.totalPrice
        }
        this.setData({
            shopIschecked: this.data.shopIschecked,
            cartList: this.data.cartList,
            shopPrice: totalPrice
        })
    },
    // 电话
    callPhone() {
        wx.makePhoneCall({
            phoneNumber: this.data.shopInfo.store.mobile,
            fail: function () { }
        })
    },
    checkAddress() { //点击地址按钮
        if (!this.data.shopInfo.store.xpoint || !this.data.shopInfo.store.ypoint) {
            common.showToast('商家未设置位置信息')
            return
        }
        let lon = parseFloat(this.data.shopInfo.store.xpoint)
        let lat = parseFloat(this.data.shopInfo.store.ypoint)
        wx.openLocation({
            latitude: lat,
            longitude: lon,
            name: this.data.shopInfo.store.name ? this.data.shopInfo.store.name : null,
            address: this.data.shopInfo.store.address ? this.data.shopInfo.store.address : null,
            scale: 18,
            fail: () => {
                wx.showToast({
                    title: '无地址信息',
                    icon: 'none'
                })
            }
        })
    },
    // 触底效果
    fnLower(e) {
        this.gong(false)
    },
    gong(refresh = false) {
        const that = this
        if (this.data.isLoadingBusy) {
            return
        }
        const pageNum = refresh ? 1 : this.data.pageNum + 1
        let tempJson = {
            pageSize: 10,
            pageNum,
            storeId: this.data.storeId
        }
        common.post('/storeArticle/getStoreArticleListForOneStore', tempJson,
            function (res) {
                that.data.pageNum = pageNum
                if (res.status === 200) {
                    that.setData({
                        articleList: res.data.list,
                        articleLists: refresh ? res.data.list : [...res.data.list, ...that.data.articleLists]
                    }, () => {
                        that.stopFn(res)
                    })
                } else {
                    common.showRequestErrMsg(res)
                    that.stopFn(res)
                }
            },
            function () {
                // that.setData({
                //     isLoadingBusy: false
                // })
            })
    },
    // 没有数据不掉接口
    stopFn(res) {
        const that = this
        if (res.data && res.data.list !== []) {
        } else {
            that.setData({
                isLoadingBusy: true
            })
        }
    },
    // 图片预览
    preview(event) {
        let { nindex, windex } = event.currentTarget.dataset
        console.log(nindex, windex)
        let pic_ce = this.data.commentList[windex].picUrls
        this.setData({
            pic_ce,
            current: nindex,
            showImg: true
        })
    },
    goDetails(e) {
        let itemId = e.currentTarget.dataset.item.id
        wx.navigateTo({
            url: `/packageC/pages/takeoutDetail/takeoutDetail?itemId=${itemId}&storeId=${this.data.storeId}`,
        })

    },
    // 获取购物车数量
    getCartNum(flag = false, id) {
        const that = this
        let tempJson = {
            storeId: that.data.storeId,
            userId: that.data.userInfo.id,
            token: that.data.token
        }
        common.wxRequest('/cart/listByStore', 'post', tempJson, 'application/x-www-form-urlencoded', function (res) {
            if (res.status === 200) {
                let totalPrice = 0;
                let totalNum = res.data.totalNum
                let arrId = []
                // console.log(flag,id,"flagflagflag")
                that.data.atherCarList.map((item, index) => {
                    if (item.shopIschecked) {
                        arrId.push(item.id)
                    }
                })

                let prices = 0
                let nn = 0
                for (let i = 0; i < res.data.list.length; i++) {
                    let item = res.data.list[i]
                    totalPrice = item.num * item.price + totalPrice
                    for (let j = 0; j < arrId.length; j++) {
                        console.log(j, "jjjjj")
                        if (j == i) {
                            item.shopIschecked = true
                            prices = item.num * item.price + prices
                            nn = item.num + nn
                        }
                    }
                }
                console.log(nn, "jhhhhhhs")
                that.setData({
                    cartList: res.data.list,
                    cartNum: totalNum,
                    goodsCount: 1,
                    totalPrice,
                    shopPrice: prices,
                    goodsNum: nn
                }, () => { })
            } else {
                that.setData({
                    cartList: [],
                    cartNum: 0,
                    goodsCount: 1,
                    totalPrice: 0
                })
                if (!flag) {
                    wx.showToast({
                        icon: 'none',
                        title: res.msg ? res.msg : '添加失败',
                    })
                }

            }
        }, () => {
            that.setData({
                isShowLoader: false  //购物车加载
            })
        })
    },
    // 店铺详情
    shopInfo() {
        var that = this
        var tempJson = {
            storeId: that.data.storeId,
            xpoint: this.data.lat,
            ypoint: this.data.lon,
            xcFlag: '0' //是否含有携程门票 0不含有
        }
        common.get('/store/mainPageInfo', tempJson, res => {
            for (let i = 0; i < res.data.couponList.length; i++) {
                that.setData({
                    industryType: res.data.store.industryType
                })
            }
            if (res.data.commentList) {
                for (var i = 0; i < res.data.commentList.length; i++) {
                    res.data.commentList[i].addTime = that.time(res.data.commentList[i].addTime)
                }
            }
            this.setData({

                commentList: res.data.commentList,
                cateLeftList: res.data.itemCatList2.storeCatList,
                activeId: res.data.itemCatList2.storeCatList.length > 0 ? res.data.itemCatList2.storeCatList[0].id : '',
                couponList: res.data.couponList,
                shopInfo: res.data,
                defaultItemList: res.data.itemCatList2.defaultItemList,
            }, () => {
                // 计算右侧商品高度
                wx.createSelectorQuery().selectAll('.cessss').boundingClientRect(function (rect) {//selectAll会选择所要含有该类名的盒子
                }).exec(function (res) {
                    that.heightArry(res)
                })
                // console.log(res.data.itemCatList2.defaultItemList)
                // this.changeCategory(that.data.activeId)
            })
        })
    },
    toArticleDetail(e) {
        const item = e.currentTarget.dataset.item
        wx.navigateTo({
            url: '/pages/discovery/articleDetail/index?id=' + item.id +
                '&storeName=' + item.storeName +
                '&title=' + item.title +
                '&createTime=' + item.createTime +
                '&storeImg=' + item.storeImg
        })
    },

    queryCollection() {
        var that = this
        var tempJson = {
            token: that.data.token,
            userId: that.data.userInfo.id,
            storeId: that.data.storeId
        };
        common.post("/store/favo/collected", tempJson, function (res) {
            // 当前接口200是关注，非200是未关注
            that.setData({
                isCollected: res.data
            })
        });
    },
    // 是否收藏
    clickCollect() {
        let that = this
        let param = that.data.isCollected ? 'delete' : 'add'
        var tempJson = {
            token: that.data.token,
            userId: that.data.userInfo.id,
            storeId: that.data.storeId
        };
        common.post("/store/favo/" + param, tempJson, function (res) {
            res.status == 200 && that.queryCollection()
        })
    },

    // 商品接口
    changeCategory(idx) {
        this.setData({
            isLoading: true
        })
        const that = this
        const tempJson = {
            storeCid: idx,
            storeId: that.data.storeId,
            token: that.data.token,
            userId: that.data.userInfo.id
        }
        common.post('/store/mainPageInfo/storeCid', tempJson, function (res) {
            if (res.status === 200) {
                that.setData({
                    defaultItemList: res.data.data
                }, () => {

                })
            } else {
                that.setData({
                    defaultItemList: []
                })
                common.showRequestErrMsg(res)
            }
        }, function () {
            that.setData({
                isLoading: false
            })
        })
    },
    // 时间戳
    time(time) {
        return common.dateFormat('yyyy-MM-dd HH:mm', time)
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {

        // let winHeight = (res.windowHeight - 10 - 40) * 750 / res.screenWidth
        console.log(wx.getSystemInfoSync().windowHeight, "屏幕")
        let screenHeight = wx.getSystemInfoSync().windowHeight
        console.log(screenHeight - 88 - 105 - 60 - 65)
        let okHeight = (screenHeight - 88 - 110 - 80 - 65)
        const that = this
        this.setData({
            toView: 'a1',
        })
        // 返回按钮
        let capsule = wx.getMenuButtonBoundingClientRect()
        this.setData({
            okHeight,
            height: capsule.height,
            top: capsule.top,
            storeId: options.id ? options.id : 1641,

        })
        // 用户信息
        common.getLocalUserInfo((success, data) => {
            if (success) {
                this.setData({
                    userInfo: data.user,
                    token: data.token,
                    openid: data.openid,
                }, () => {
                    this.clickCollect()  //是否收藏
                    this.gong(true)
                    this.queryCollection()
                    this.getCartNum(true)
                })
            }
        }, true)

        // 定位
        that.getLocation()
    },
    // 获取当前定位
    getLocation() {
        app.getLocation(
            (data) => {
                this.setData({
                    lon: data.longitude,
                    lat: data.latitude
                }, () => {
                    this.shopInfo()
                })
            },
            (err) => {
                // 定位失败回调
                this.setData({
                    refreshing: false
                })
            })
    },
    // 右侧商品的高度
    heightArry(res) {
        let h = 0;
        let heightArr = [];
        res[0].forEach((item) => {
            h += item.height;
            heightArr.push(h);
        })
        this.setData({ heightArr: heightArr })
    },
    // 滚动事件
    Right_Scroll(e) {
        const that = this
        if (!that.data.clickShow) {
            let scrollHeight = e.detail.scrollTop;
            let index = this.calculateIndex(this.data.heightArr, scrollHeight);
            console.log(index)
            this.setData({
                activeId: this.data.defaultItemList[index].storeCid
            }, () => {
            })
        }
        this.setData({
            clickShow: false
        })

    },
    // 计算左边选中的下标
    calculateIndex(arr, scrollHeight) {
        let index = '';
        for (let i = 0; i < arr.length; i++) {
            if (scrollHeight >= 0 && scrollHeight < arr[0]) {
                index = 0;
            } else if (scrollHeight >= arr[i - 1] && scrollHeight < arr[i]) {
                index = i;
            }
        }
        return index;
    },
    // 二级分类点击
    clickItem(e) {
        const that = this
        this.setData({
            activeId: e.currentTarget.dataset.id,
            toView: e.currentTarget.dataset.id,
            clickShow: true
        }, () => {

            // that.changeCategory(e.currentTarget.dataset.id)
            //    const index =  that.data.defaultItemList.findIndex((i)=>{
            //          return i.storeCid === this.data.activeId
            //     })
            //     console.log(index)
            //     console.log(this.data.heightArr)
        })
    },
    // tabs切换
    click_item(e) {
        let index = e.currentTarget.dataset.index
        this.setData({
            actIndex: index
        })
    },
    // 点击收藏
    clickCollect() {
        let that = this
        let param = that.data.isCollected ? 'delete' : 'add'
        var tempJson = {
            token: that.data.token,
            userId: that.data.userInfo.id,
            storeId: that.data.storeId
        };
        common.post("/store/favo/" + param, tempJson, function (res) {
            res.status == 200 && that.queryCollection()
        })

    },
    // 选规格
    go_guige() {
        this.setData({
            guigeShow: true
        })
    },
    onClose() {
        this.setData({
            guigeShow: false
        });
    },
    // 商品规格
    clickGetDishAttrList(e) {
        let that = this
        let { id, item } = e.currentTarget.dataset
        let tempJson = {
            itemId: id,

        }
        that.setData({
            itemId: id,
            goodsNei: item
        })
        common.post("/item/getDishAttrList", tempJson, function (res) {
            let checkedStr = '';

            for (let i = 0; i < res.data.length; i++) {
                if (i !== res.data.length - 1) {
                    checkedStr = checkedStr + res.data[i].attrValueList[0].attrValue + '/'
                } else {
                    checkedStr = checkedStr + res.data[res.data.length - 1].attrValueList[0].attrValue
                }

            }

            that.setData({
                attrValueList: res.data,
                checkedAttr: checkedStr
            })
        })
    },
    clickGoodsCount(e) {
        this.setData({
            goodsCount: e.detail,
        }, () => {
            // this.submitAddCart()
        })
    },
    // 添加购物车
    submitAddCart() {
        const that = this
        const num = this.data.goodsCount
        const itemId = this.data.itemId
        if (!num) {
            common.showToast('没有添加数量')
            return
        }
        let tempJson = {
            dishFlavor: that.data.checkedAttr,
            userId: that.data.userInfo.id,
            token: that.data.token,
            itemId,
            num
        }
        common.wxRequest('/cart/add', 'post', tempJson, 'application/x-www-form-urlencoded', function (res) {
            if (res.status === 200) {
                that.closeAddCart()
                that.getCartNum()  //获取
                that.setData({
                    goodsCount: 1,
                })
                wx.showToast({
                    title: '添加成功!',
                })
            } else {
                wx.showToast({
                    icon: 'loading',
                    title: res.msg ? res.msg : '添加失败',
                })
            }
        })
    },
    closeAddCart() {
        this.setData({
            guigeShow: false
        })
    },
    // 点击购物车
    click_shoppcar() {
        this.setData({
            shopCarShow: true
        }, () => {
            this.getCartNum()
        })
    },
    // 清空购物车    userId  cartIds  删除或者多个
    clearCart() {
        const that = this
        let arrList = []
        for (let i = 0; i < that.data.cartList.length; i++) {
            arrList.push(that.data.cartList[i].id)
        }

        this.setData({
            isShowLoader: true
        })
        let tempJson = {
            cartIds: arrList.toString(),
            userId: that.data.userInfo.id,
            token: that.data.token
        }
        common.wxRequest('/cart/deleteByCartId ', 'post', tempJson, 'application/x-www-form-urlencoded', function (res) {
            if (res.status === 200) {
                // that.onCloses()
                that.setData({
                    shopPrice: 0,
                    shopIschecked: false
                })
                that.getCartNum()
            } else {
                wx.showToast({
                    title: res.msg ? res.msg : '添加失败',
                })
            }
        })
    },
    // 返回上页面
    goBack() {
        const pages = getCurrentPages();
        const prevPage = pages[pages.length - 2]; //上一个页面
        // 从朋友圈进入的时候，页面栈为空，这里需要判断是否有上个页面
        if (prevPage) {
            wx.navigateBack({
                delta: 1
            })
        } else {
            wx.redirectTo({
                url: '/pages/index/index',
            })
        }
    },
    // 购物车关闭
    onCloses() {
        this.setData({
            shopCarShow: false
        })
    },
    //购物车减少一
    onminus(e) {
        let item = e.currentTarget.dataset.item
        let cartId = item.id
        console.log(item, "lllllllllllllllllllllllllllllllllllllll")
        this.changeCartNum(-1, cartId, item.itemId)

    },
    //  购物车增加1
    onplus(e) {
        let { index, item } = e.currentTarget.dataset
        let cartId = item.id

        // this.setData({
        //   shopPrice
        // })

        this.changeCartNum(1, cartId, item.itemId)
    },
    //购物车加一
    changeCartNum(num, cartId, itemId) {
        const that = this
        this.setData({
            isShowLoader: true
        })
        let tempJson = {
            itemId: itemId,
            token: that.data.token,
            cartId,
            num,
            userId: that.data.userInfo.id,
        }
        common.wxRequest('/cart/updateOneByCartId', 'POST', tempJson, 'application/x-www-form-urlencoded', function (res) {
            if (res.status === 200) {
                that.getCartNum(false, cartId)
            } else {
                wx.showToast({
                    title: res.msg ? res.msg : '添加失败',
                })
            }
        })
    },
    // 购物车输入改变
    onblur(e) {
        const that = this
        let { item } = e.currentTarget.dataset
        let num = e.detail.value
        let cartId = item.id
        that.inputCartNum(num, cartId, item.itemId)

    },
    //  输入input改变     userId cartId num   修改数量
    inputCartNum(num, cartId) {
        const that = this
        this.setData({
            isShowLoader: true
        })
        let tempJson = {
            cartId,
            num,
            userId: that.data.userInfo.id,
            token: that.data.token
        }
        common.wxRequest('/cart/updateNumByCartId', 'post', tempJson, 'application/x-www-form-urlencoded', function (res) {
            if (res.status === 200) {
                that.onCloses()
                that.getCartNum()
            } else {
                wx.showToast({
                    title: res.msg ? res.msg : '添加失败',
                })
            }
        })
    },
    //    立即结算
    go_balance() {
        if (this.data.cartNum == 0) {
            return
        }
        wx.navigateTo({
            url: `/packageC/pages/takeoutOrder/takeoutOrder?storeId=${this.data.storeId}&totalPrice=${this.data.totalPrice}&storeId=${this.data.storeId}`,
        })
    },
})